package cn.qidisoft.edu.hzjt.controller.zyc;


import cn.qidisoft.core.common.context.ApplicationContextConfigUtil;
import cn.qidisoft.core.common.log.LoggerAdapter;
import cn.qidisoft.core.common.log.LoggerAdapterFactory;
import cn.qidisoft.core.common.pagination.Page;
import cn.qidisoft.core.common.pagination.PaginationBean;
import cn.qidisoft.core.util.file.FileUtil;
import cn.qidisoft.core.util.moffice.excel.ExpExcelUtil;
import cn.qidisoft.core.util.uuid.UUIDGenerator;
import cn.qidisoft.edu.hzjt.constants.Constant;
import cn.qidisoft.edu.hzjt.controller.BaseController;
import cn.qidisoft.edu.hzjt.exception.RPCException;
import cn.qidisoft.edu.hzjt.model.BjxxClassMaterialFile;
import cn.qidisoft.edu.hzjt.model.ResponseResult;
import cn.qidisoft.edu.hzjt.model.UserEmployee;
import cn.qidisoft.edu.hzjt.model.zyc.DevelopmentPlanning;
import cn.qidisoft.edu.hzjt.model.zyc.DevelopmentPlanningAtt;
import cn.qidisoft.edu.hzjt.service.zyc.IDevelopmentPlanningAttService;
import cn.qidisoft.edu.hzjt.service.zyc.IDevelopmentPlanningService;
import cn.qidisoft.edu.hzjt.utils.CommonUtils;
import cn.qidisoft.edu.hzjt.utils.LogType;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.FilenameUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 学校发展规划——CellId：JKY_JKS_XXFZGH
 * @author zhangwenliang
 * @Date  2018.11.27
 *
 */

@Controller
@RequestMapping(value = "developmentPlanning")
public class DevelopmentPlanningController {

    protected static final LoggerAdapter LOGGER =
            LoggerAdapterFactory.getLogger(LogType.HZJT_LOGGER.val);

    @Autowired
    private IDevelopmentPlanningService DevelopmentPlanningService;  
    
    @Autowired
    private IDevelopmentPlanningAttService developmentPlanningAttService; 

    private static String upload = null;

    static {
        upload = ApplicationContextConfigUtil.getString("file.path", null);
    }

    private static Map<String, List<DevelopmentPlanningAtt>> picMap = new HashMap<>();

    @RequestMapping(value = "/index")
    public String index(ModelMap model, HttpServletRequest request) {
        request.setAttribute("msg", BaseController.getParameter("msg"));
        BaseController.removeParameter("msg");
        return "zyc/developmentPlanning/developmentPlanningList";
    }
    @RequestMapping(value = "/list")
    @ResponseBody
    public ResponseResult list(
            ModelMap model, HttpServletRequest request,
            @RequestParam(value = "rows", required = false) String pageSize,
            @RequestParam(value = "page", required = false) String currentPage,
            DevelopmentPlanning data) {
        try {
            data.setGid(UUIDGenerator.genReqID());
            Page page = new Page();
            page.setCurrPage(currentPage == null ? 0 : Integer.valueOf(currentPage));
            page.setPageSize(pageSize == null ? Constant.PageSize : Integer.valueOf(pageSize));
            BaseController.setSortByColumn(request, "createTime", "desc");
            data.setOrderField((String) request.getAttribute("orderField"));
            data.setOrderFlag((String) request.getAttribute("orderFlag"));
        	Map<String, Object> queryMap = new HashMap<String, Object>();
    		String begintime = request.getParameter("begintime");
    		String endtime = request.getParameter("endtime");
    	    queryMap.put("DevelopmentPlanning", data);
    		queryMap.put("begintime", begintime);
    		queryMap.put("endtime", endtime);
    		String title = request.getParameter("title");
    		System.out.println("+++" + title);
    		if(null != title) {
    			title = title.trim();
    		}
    		String creatorname = request.getParameter("creatorname");
    		if(null != creatorname) {
    			creatorname = creatorname.trim();
    		}
    		queryMap.put("title", title);
    		queryMap.put("creatorname",creatorname);
            PaginationBean<DevelopmentPlanning> paginationBean = DevelopmentPlanningService.queryPageList(queryMap, page);
            ResponseResult result = new ResponseResult();
            result.setTotal(paginationBean.getTotalRecords());
            result.setRows(paginationBean.getPageList());
            return result;
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
        return null;
    }

    @RequestMapping(value = "/addInInt", method = RequestMethod.GET)
    public String add(ModelMap model, HttpServletRequest request) {
        UserEmployee userEmployee =
                (UserEmployee) request.getSession().getAttribute(Constant.LOGIN_CONSOLE_USER);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String today = dateFormat.format(new Date());
        Map<String, Object> reMap = new HashMap<>();
        reMap.put("createTime", today);
        reMap.put("creatorName", userEmployee.getXm());
        request.setAttribute("entity", reMap);
        request.setAttribute("msg", BaseController.getParameter("msg"));
        BaseController.removeParameter("msg");
        return "zyc/developmentPlanning/developmentPlanningAdd";
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public String save(ModelMap model, HttpServletRequest request,
                       DevelopmentPlanning data) {
        try {
            UserEmployee userEmployee =
                    (UserEmployee) request.getSession().getAttribute(Constant.LOGIN_CONSOLE_USER);
            String action = request.getParameter("action")==null?"":request.getParameter("action");
            	//data.setXkid(userEmployee.getEmid());
        	data.setGid(UUIDGenerator.genReqID());
        	data.setCreatorId(userEmployee.getUid());
        	data.setCreatorName(userEmployee.getXm());
        	SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String formatStr =formatter.format(new Date());
        	data.setCreateTime(formatStr);
        	DevelopmentPlanningService.insert(data);      	
         
            	
            String path = upload;
            List<DevelopmentPlanningAtt> docFileResourceList = picMap.get(String.valueOf(userEmployee.getUserid()));
            if (docFileResourceList != null && !docFileResourceList.isEmpty()) {
                MultipartFile file = null;
                String filePath =CommonUtils.createSaveFilePath("JKY_JKS_XXFZGH", userEmployee.getUserid() );
                int orders = 0;
                for (DevelopmentPlanningAtt r : docFileResourceList) {
                    file = r.getMufile();
                    r.setParentId(data.getFzid());
                    String name = file.getOriginalFilename();// 获取上传文件名
                    InputStream in = r.getInputStream();// 获取文件对象
                    int pos = name.lastIndexOf(".");
                    String lastname = name.substring(pos, name.length());
                    // 文件保存的路径
                    String savePath = path + CommonUtils.fileSeprator + filePath;
                    FileUtil.saveFile(savePath, in, r.getGid() + lastname);
                    r.setGid(r.getGid());// 附件id
                    r.setFileName(name);
                    r.setOrders(orders);
                    orders++;
                }
                developmentPlanningAttService.batchInserts(docFileResourceList);
                //保存成功后，清除明细
                picMap.remove(String.valueOf(userEmployee.getUserid()));
            }
            BaseController.setParameter("msg", "添加成功");
            if (action.equals("add")) {
                return "redirect:addInInt";
            }else{
                return "redirect:./view?fzid=" + data.getFzid();
            }
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("添加信息 add [{}] error," + this.getClass().getName() + "=[{}]",
                    this.getClass().getName(), e.getMessage());
            return "error/error";
        }
    }
    /**
	 * 进入预览页面
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("view")
	public String view(ModelMap model, HttpServletRequest request) {
		try {
			String  fzid = request.getParameter("fzid");
            // 查询发展规划信息
			DevelopmentPlanning development = new DevelopmentPlanning();
			development.setFzid(Integer.parseInt(fzid));
			DevelopmentPlanning developmentPlanning = DevelopmentPlanningService.getPlanning(development);
			if(null != developmentPlanning.getKsrq()) {
				developmentPlanning.setKsrq(developmentPlanning.getKsrq().substring(0, developmentPlanning.getKsrq().length()-2));  
			}
			if(null != developmentPlanning.getJsrq()) {
				developmentPlanning.setJsrq(developmentPlanning.getJsrq().substring(0, developmentPlanning.getJsrq().length()-2));   				
   			}
   			if(null != developmentPlanning.getCreateTime()) {
   				developmentPlanning.setCreateTime(developmentPlanning.getCreateTime().substring(0, developmentPlanning.getCreateTime().length()-2));   				
   			}
			// 查询附件信息
			List<DevelopmentPlanningAtt> dataList = developmentPlanningAttService.getPlanningAtt(development);
			request.setAttribute("data", developmentPlanning);
			request.setAttribute("dataList", dataList);
			return "zyc/developmentPlanning/view";
		} catch (Exception e) {
			LOGGER.error("获得xxxxx信息 addStudentDemoForward [{}] error," + this.getClass().getName() + "=[{}]",
					this.getClass().getName(), e.getMessage());
			return "error/error";
		}
	}
	/**
	 * 跳转到修改页面
	 * 编辑该党员的明细打分页面，仅浏览、编辑一个人的打分信息
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("edit")
	public String edit(ModelMap model, HttpServletRequest request) {
		try {
			String  fzid = request.getParameter("fzid");
            // 查询发展规划信息
			DevelopmentPlanning development = new DevelopmentPlanning();
			development.setFzid(Integer.parseInt(fzid));
			DevelopmentPlanning developmentPlanning = DevelopmentPlanningService.getPlanning(development);
			if(null != developmentPlanning.getKsrq()) {
				developmentPlanning.setKsrq(developmentPlanning.getKsrq().substring(0, developmentPlanning.getKsrq().length()-2));  
			}
			if(null != developmentPlanning.getJsrq()) {
				developmentPlanning.setJsrq(developmentPlanning.getJsrq().substring(0, developmentPlanning.getJsrq().length()-2));   				
   			}
   			if(null != developmentPlanning.getCreateTime()) {
   				developmentPlanning.setCreateTime(developmentPlanning.getCreateTime().substring(0, developmentPlanning.getCreateTime().length()-2));   				
   			}
			// 查询附件信息
			List<DevelopmentPlanningAtt> dataList = developmentPlanningAttService.getPlanningAtt(development);
			request.setAttribute("data", developmentPlanning);
			request.setAttribute("dataList", dataList);
			return "zyc/developmentPlanning/edit";
		} catch (Exception e) {
			LOGGER.error("获得xxxxx信息 addStudentDemoForward [{}] error," + this.getClass().getName() + "=[{}]",
					this.getClass().getName(), e.getMessage());
			return "error/error";
		}
	}
	 @RequestMapping(value = "/update", method = RequestMethod.POST)
	    public String update(ModelMap model, HttpServletRequest request,
	                       DevelopmentPlanning data) {
	        try {
	            UserEmployee userEmployee =
	                    (UserEmployee) request.getSession().getAttribute(Constant.LOGIN_CONSOLE_USER);
	            String action = request.getParameter("action")==null?"":request.getParameter("action");
	            	//data.setXkid(userEmployee.getEmid());
	        	data.setGid(UUIDGenerator.genReqID());
	        	data.setCreatorId(userEmployee.getUid());
	        	data.setCreatorName(userEmployee.getXm());
	        	SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				String formatStr =formatter.format(new Date());
	        	data.setCreateTime(formatStr);
	        	DevelopmentPlanningService.update(data);
	         
	            	
	            String path = upload;
	            List<DevelopmentPlanningAtt> docFileResourceList = picMap.get(String.valueOf(userEmployee.getUserid()));
	            if (docFileResourceList != null && !docFileResourceList.isEmpty()) {
	                MultipartFile file = null;
	                String filePath =CommonUtils.createSaveFilePath("JKY_JKS_XXFZGH", userEmployee.getUserid() );
	                int orders = 0;
	                for (DevelopmentPlanningAtt r : docFileResourceList) {
	                    file = r.getMufile();
	                    r.setParentId(data.getFzid());
	                    String name = file.getOriginalFilename();// 获取上传文件名
	                    InputStream in = r.getInputStream();// 获取文件对象
	                    int pos = name.lastIndexOf(".");
	                    String lastname = name.substring(pos, name.length());
	                    // 文件保存的路径
	                    String savePath = path + CommonUtils.fileSeprator + filePath;
	                    FileUtil.saveFile(savePath, in, r.getGid() + lastname);
	                    r.setGid(r.getGid());// 附件id
	                    r.setFileName(name);
	                    r.setOrders(orders);
	                    orders++;
	                }
	                developmentPlanningAttService.batchInserts(docFileResourceList);
	                //保存成功后，清除明细
	                picMap.remove(String.valueOf(userEmployee.getUserid()));
	            }
	            BaseController.setParameter("msg", "添加成功");
	            if (action.equals("add")) {
	                return "redirect:addInInt";
	            }else{
	                return "redirect:./view?fzid=" + data.getFzid();
	            }
	        } catch (Exception e) {
	            e.printStackTrace();
	            LOGGER.error("添加信息 add [{}] error," + this.getClass().getName() + "=[{}]",
	                    this.getClass().getName(), e.getMessage());
	            return "error/error";
	        }
	    }
	
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public String delete(ModelMap model, HttpServletRequest request) {
        try {
            String[] idList = request.getParameter("idList").split(",");
            DevelopmentPlanning data = new DevelopmentPlanning();
            data.setIds(idList);
            DevelopmentPlanningService.delete(data);
            BaseController.setParameter("msg", "删除成功");
            return "redirect:index";
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("删除 delete [{}] error," + this.getClass().getName() + "=[{}]",
                    this.getClass().getName(), e.getMessage());
            return "error/error";
        }
    }

    /**
     * 上传
     *
     * @param file
     * @param request
     * @param response
     */
    @RequestMapping(value = "/source_upload", method = RequestMethod.POST)
    public @ResponseBody void loadFile(@RequestParam("file") MultipartFile file,
                                       HttpServletRequest request, HttpServletResponse response) {
        List<DevelopmentPlanningAtt> list = new ArrayList<DevelopmentPlanningAtt>();
        UserEmployee userEmployee = (UserEmployee) request.getSession()
                .getAttribute(Constant.LOGIN_CONSOLE_USER);
        List<DevelopmentPlanningAtt> docFileResourceList = picMap
                .get(String.valueOf(userEmployee.getUserid()));
        // 本地env配置路径
        String path = upload;
        try {
            String gid = UUID.randomUUID().toString();
            String name = file.getOriginalFilename();// 获取上传文件名
            // 获取文件后缀名称
            String extend = FilenameUtils.getExtension(name);
            DevelopmentPlanningAtt docFile = new DevelopmentPlanningAtt();
            String filePath =CommonUtils.createSaveFilePath("JKY_JKS_XXFZGH", userEmployee.getUserid() );
            if (!file.isEmpty()) {
                // 文件的大小
                docFile.setFileSize(String.valueOf(FileUtil.FormetFileSize(Long.valueOf(file.getSize()))));
                docFile.setFileName(name);
                docFile.setGid(gid);
                docFile.setExtension(FileUtil.getFileExtendName(name).toLowerCase());
                docFile.setMufile(file);
                docFile.setInputStream(file.getInputStream());
                /**
                 * 2018.12.10
                 * 当前业务目录/用户ID/上传当前时间（到天）/随机生成uuid文件名称
                 */
                docFile.setFilePath(filePath + gid + "." + extend);
				docFile.setSysfilepath(path + CommonUtils.fileSeprator + filePath + gid + "." + extend);
				
				docFile.setOrders(0);
                if (docFileResourceList != null && docFileResourceList.size() > 0) {
                    docFileResourceList.add(docFile);
                    picMap.put(String.valueOf(userEmployee.getUserid()), docFileResourceList);
                } else {
                    list.add(docFile);
                    picMap.put(String.valueOf(userEmployee.getUserid()), list);
                }
                LOGGER.info("附件上传成功！");
            }
            PrintWriter writer = null;
            BjxxClassMaterialFile docFile2 = new BjxxClassMaterialFile();
            docFile2.setFilepath(docFile.getFilePath());
            // 文件名称
            docFile2.setFilename(docFile.getFileName());
            docFile2.setSysfilepath(path + CommonUtils.fileSeprator + filePath + gid + "." + extend);
            writer = response.getWriter();
            String json = JSONObject.toJSONString(docFile2);
            writer.write(json);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
  	 * 
  	 * @Title: source_upload_update @Description: 删除附件 @param @param
  	 *         fileId @param @param request @param @param response @param @return
  	 *         参数 @return Map<String,Object> 返回类型 @throws
  	 */
  	@RequestMapping(value = "/source_upload_update", method = RequestMethod.POST)
  	public @ResponseBody Map<String, Object> source_upload_update(@RequestParam("fileId") String fileId,
  			@RequestParam("filePath") String filePath, HttpServletRequest request, HttpServletResponse response) {
  		Map<String, Object> dataMap = new HashMap<String, Object>();
  		try {
  			// 删除表记录
  			DevelopmentPlanningAtt attEntity = new DevelopmentPlanningAtt();
  			attEntity.setFileId(Integer.parseInt(fileId));
  			
  			DevelopmentPlanningAtt newAttEntity = developmentPlanningAttService.queryByFileId(attEntity);
  			filePath = newAttEntity.getFilePath();
  			developmentPlanningAttService.deleteAccessory(attEntity);
  			
  			// 删除原始文件
  			File file = new File(upload + CommonUtils.fileSeprator + filePath);
  			file.delete();
  			
  			dataMap.put("success", "0000");
  		} catch (Exception e) {
  			LOGGER.error("调用services网络异常", e);
  			dataMap.put("success", "-9999");
  		}
  		return dataMap;
  	}
    /**
	 * 学校发展规划下载
	 * 
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "export_developmentPlanning")
	public @ResponseBody void export_dzb(HttpServletRequest request, HttpServletResponse response,DevelopmentPlanning data) throws Exception {
		try {
			Map<String, Object> queryMap = new HashMap<String, Object>();
    		String begintime = request.getParameter("begintime");
    		String endtime = request.getParameter("endtime");
    	    queryMap.put("DevelopmentPlanning", data);
    		queryMap.put("begintime", begintime);
    		queryMap.put("endtime", endtime);
    		queryMap.put("title", request.getParameter("subject"));
    		queryMap.put("creatorname",request.getParameter("creatorName"));
			List<DevelopmentPlanning> datalist = DevelopmentPlanningService.getPlanningList(queryMap);
			String[][] title_name = { { "id", "标题", "开始日期", "结束日期", "创建人", "创建日期"} };
			String[] title_style = { "hwzs_16_bold_25","hwzs_16_bold_25","hwzs_16_bold_25","hwzs_16_bold_25", "hwzs_16_bold_25",
					"hwzs_16_bold_25" };
			String fileName = "学校发展规划信息";
			String[] remark = { "" };
			List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
			if (datalist != null && !datalist.isEmpty()) {
				for (DevelopmentPlanning res : datalist) {
					Map<String, Object> map = new LinkedHashMap<String, Object>();
					map.put("fzid", res.getFzid());
					map.put("subject", res.getSubject());
					map.put("ksrq", res.getKsrq());
					map.put("jsrq", res.getJsrq());
					map.put("creatorname", res.getCreatorName());
					map.put("createtime", res.getCreateTime());
					list.add(map);
				}
			}
			HSSFWorkbook wb = ExpExcelUtil.getWorkBookExcel(title_name, title_style, 100, remark, fileName, list);
			try {
				String filenameConvert = "学校发展规划信息";/* new String(fileName.getBytes("GB2312"), "ISO8859-1"); */
				response.reset();
				response.setContentType("application/vnd.ms-excel;charset=utf-8");
				response.setHeader("Content-Disposition",
						"attachment;filename=" + new String((filenameConvert + ".xls").getBytes(), "iso-8859-1"));
				response.setDateHeader("Expires", 0);
				ServletOutputStream os = response.getOutputStream();
				wb.write(os);
				os.flush();
			} catch (Exception e) {
				System.out.println("网络连接断开，可能用户取消了导出");
			}
		} catch (RPCException e) {
			LOGGER.error("获得xxxxx信息 exportStudentjobList [{}] error," + this.getClass().getName() + "=[{}]",
					this.getClass().getName(), e.getMessage());
		}
	}
    
    /**
     * 新增删除服务器的文件
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/deletefile", method = RequestMethod.POST)
    public @ResponseBody Map<String, Object> deleteFile(HttpServletRequest request) {

        Map<String, Object> dataMap = new HashMap<String, Object>();
        try {
            UserEmployee userEmployee = (UserEmployee) request.getSession()
                    .getAttribute(Constant.LOGIN_CONSOLE_USER);
            // env配置路径
            String path = upload;
            String filepath = request.getParameter("filepath");
            LOGGER.info("文件的原始路径===" + filepath);
            // 文件的全路径
            String fullpath = null;
            // 文件名称
            String filename = null;
            // 文件名无后缀
            String fileNoSuffix = null;
            if (filepath.indexOf("prefix") == -1) {
                // 文件的文件名称
                fileNoSuffix = filepath.split(",")[0];
                String sec = filepath.split(",")[1];
                // 文件的后缀
                String suffix = sec.substring(sec.indexOf("."));
                // 文件名无后缀加上后缀
                filename = fileNoSuffix + suffix;
                // 文件的全路径
                fullpath = path + CommonUtils.fileSeprator + fileNoSuffix;
                // FileUtil.deleteFile(fullpath, filename);//删除文件目录下面的文件
                // FileUtils.forceDelete(new File(fullpath)); //删除文件目录
            } else {
                return dataMap;
            }
            List<DevelopmentPlanningAtt> noticeNewsFilepathList = picMap
                    .get(String.valueOf(userEmployee.getUserid()));
            // 删除list里面前台删除的前台信息图片附件表
            if (noticeNewsFilepathList != null && !noticeNewsFilepathList.isEmpty()) {
                for (DevelopmentPlanningAtt obj : noticeNewsFilepathList) {
                    if (obj.getFileName().equals(fileNoSuffix)) {
                        noticeNewsFilepathList.remove(obj);
                        break;
                    }
                }
            }
            // 先删除
            picMap.remove(userEmployee.getUserid());
            // 后添加
            picMap.put(String.valueOf(userEmployee.getUserid()), noticeNewsFilepathList);
            dataMap.put("success", "0000");
            return dataMap;
        } catch (Exception e) {
            dataMap.put("success", "-9999");
            return dataMap;
        }
    }
}
